package com.greatchn.no_session_auth_code.filter;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.greatchn.no_session_auth_code.exception.ApiException;
import com.greatchn.no_session_auth_code.util.Result;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * @ExceptionFilter: 异常过滤
 * @author: ZBoHang
 * @time: 2023/2/9 11:44
 */
@Component
public class ExceptionFilter extends ExceptionTranslationFilter {

    public ExceptionFilter(AuthenticationEntryPoint authenticationEntryPoint) {
        super(authenticationEntryPoint);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        try {
            super.doFilter(request, response, chain);
        } catch (Exception e) {
            if (e instanceof ApiException) {
                response.setContentType(ContentType.JSON.getValue());
                response.setCharacterEncoding(CharsetUtil.UTF_8);
                ApiException apiException = (ApiException) e;
                response.getWriter().write(JSONUtil.toJsonPrettyStr(Result.failure(apiException.getCode(), apiException.getMsg())));
                return;
            }
            e.printStackTrace();
        }
    }
}
